angular.module('PrintService', [])
    .controller('printManageCtrl', ['$scope', '$http', function ($scope, $http) {
        $scope.data = {
            tenantId: "",
            print_token: "",
            classMode: true,
            classList: [],
            dataList: [],
            isMounted: false
        };
        $scope.control = {
            loading: true
        };

        $scope.goSetting = function () {
            location.href ="http://"+location.host+"/PrintService/setting";
        };

        $scope.showAddDialog = function (boinfo) {
            var self = this;
            var bonameTpl = "";
            if (self.classMode) { //按分类显示时，数据源为选择框
                bonameTpl += "<select id='bo-name'>";
                for (i in boinfo.source) {
                    var bo = boinfo.source[i];
                    bonameTpl += "<option value='" + bo.bo_code + "'>" + bo.bo_name + "</option>"
                }
                bonameTpl += "</select>";
            } else { //按数据源显示时，数据源为输入框
                bonameTpl += "<input id='bo-name' readonly='true' style='background: #f1f1f1'\
						 value='" + boinfo.bo_name + "' bocode='" + boinfo.bo_code + "'>"
            }
            bootbox.dialog({
                title: "新建模板<span class='modal-line'></span>",
                message: "<div class='label-input'>\
						<label>模板编码 <span class='must-star'>*</span></label>\
						<input id='tpl-name' placeholder='请输入模板编码' value=''>\
					</div>\
					<div class='label-input'>\
						<label>数据源</label>" + bonameTpl + "</div>",
                buttons: {
                    confirm: {
                        label: '确认',
                        className: 'btn-primary',
                        callback: function () {
                            var bocode = self.classMode ? $("#bo-name").val() : $("#bo-name").attr("bocode");
                            var newtpl = $("#tpl-name").val().trim();
                            if (newtpl) {
                                var url = "http://"+location.host + "/print_service/print/design?tenantId=" + $scope.data.tenantId + "&bocode=" + bocode + "&reportName=" + newtpl + "&type=48a8206f-6759-431e-bf84-e973935e2fcc";
                                url = encodeURI(encodeURI(url));
                                window.open(url);
                                addComplete();
                            } else {
                                //TODO
                                $("#tpl-name").focus();
                            }
                        }
                    },
                    cancel: {
                        label: '取消',
                        className: 'btn-cancel'
                    }
                }
            })
        };

        $scope.templateDesign = function (tplinfo) {
            var url = "http://"+location.host + "/print_service/print/design?tenantId=" + $scope.data.tenantId + "&printcode=" + tplinfo.templatecode;
            url = encodeURI(encodeURI(url));
            window.open(url);
        };

        $scope.templateCopy = function (bo, tplinfo) {
            var self = this;
            bootbox.dialog({
                title: "复制模板<span class='modal-line'></span>",
                message: "<div class='label-input'>" +
                "<label>模板名称 <span class='must-star'>*</span></label>" +
                "<input id='copy-name' placeholder='' value='" + tplinfo.templatename +
                "_副本' 	code='" + tplinfo.templatecode + "'pk='" + tplinfo.pk_print_template + "'>" +
                " <\div>",
                buttons: {
                    confirm: {
                        label: "确认",
                        className: "btn-primary",
                        callback: function () {
                            $scope.control.loading = true;
                            var time = new Date().getTime();
                            $.ajax({
                                type: "post",
                                url: "copyTemByPk",
                                data: {
                                    pk_bo: bo.pk_bo,
                                    pk_print_template: $("#copy-name").attr("pk"),
                                    copytemplatecode: "T" + time,
                                    copytemplatename: $("#copy-name").val().trim()
                                },
                                async: false,
                                success: function (data) {
                                    if (data) {
                                        if (data.copyMsg) {
                                            showMessage("模板复制成功！");
                                            $scope.syscBOTempInfo();
                                        } else {
                                            showMessage(data.copyResult ? data.copyResult : "模板复制失败！")
                                        }
                                    } else {
                                        showMessage("返回数据为空，请刷新重试。");
                                    }
                                },
                                error: function(){
                                    showMessage("服务连接错误，请检查！");
                                },
                                complete:function(XHR, TS){
                                    $scope.control.loading = false;
                                }
                            })
                        }
                    },
                    cancel: {
                        label: "取消",
                        className: "btn-cancel"
                    }
                }
            })
        };

        $scope.templatePreview = function (boInfo, tplinfo) {
            var printData = [
                {
                    Barcode: "1502162218039715",
                    BarcodeName: "已上线",
                    TagName: "标签",
                    DocNo:"2034234111"
                },
                {
                    Barcode: "1502162218039714",
                    BarcodeName: "工位",
                    TagName: "标签",
                    DocNo:"2034234111"
                }
            ];
            var tenantId = $scope.data.tenantId;
            if (tplinfo.issystem) {
                tenantId = null;
            }
            //回调本地服务取数据
            var dataUrl = "http://"+location.host+ "/PrintService/templatePreview";
            var template = tplinfo.templatecode;
            var params = JSON.stringify({
                printData: printData,
                boCode: boInfo.bo_code
            });
            var url = "http://"+location.host+ '/print_service/print/preview?tenantId=' + $scope.data.tenantId + '&template=' + template + '&printcode=' + template + '&serverUrl=' + dataUrl + '&params=' + params + '&sendType=2';
            window.open(url);
        };

        $scope.templateDelete = function (tpl) {
            $scope.control.loading = true;
            $http({
                method: "post",
                url: "deleteTemplate",
                params: {
                    pk_print_template: tpl.pk_print_template
                }
            }).then(function (result) {
                if (result.data.delresult) {
                    showMessage("删除成功！");
                    getClassList();
                } else {
                    showMessage("删除失败，请检查！");
                }
            }, function (err) {
                showMessage("删除失败，请检查！");
            }).finally(function () {
                $scope.control.loading = false;
            });
        };

        function created() {
            $scope.syscBOTempInfo();
            sortTemplates();
        }

        function mounted() {
            $scope.data.isMounted = true;
            $scope.control.loading = false;
        }

        function sortTemplates() {
            var currList = $scope.data.classMode ? $scope.data.classList : $scope.data.dataList;
            currList.forEach(function (g) {
                var temp = g.template;
                var temp1 = temp.filter(function (i) {
                    return i.issystem
                })
                var temp2 = temp.filter(function (i) {
                    return !i.issystem
                })
                g.template = temp1.concat(temp2);
            })
        }

        function showMessage(message) {
            var dialog = bootbox.alert({
                message: message + "<span class='modal-line'></span>"
            });
            setTimeout(function () {
                dialog.modal('hide')
            }, 2000)
        }

        function getClassList() {
            var self = this;
            $.ajax({
                type: "post",
                url: "querybo",
                data: {},
                async: false,
                success: function (data) {
                    if (data) {
                        var templates = data.templates;
                        $scope.data.tenantId = data.tenantId;
                        $scope.data.print_token = data.print_token;
                        if (templates) {
                            $scope.data.classList = [];
                            var boList = {};
                            for (var i =0;i<templates.length;i++) {
                                setSystem(templates[i]);
                                if(boList[templates[i].bo_code]){
                                    if(templates[i].issystem){
                                        boList[templates[i].bo_code].template.unshift(templates[i]);
                                    }else{
                                        boList[templates[i].bo_code].template.push(templates[i]);
                                    }
                                }else{
                                    boList[templates[i].bo_code] = {
                                        bo_code:templates[i].bo_code,
                                        bo_name:templates[i].bo_name,
                                        template:[templates[i]]
                                    }
                                }
                            }
                            for(var x in boList){
                                $scope.data.classList.push(boList[x]);
                            }
                        }
                    } else {
                        showMessage("返回数据为空，请刷新重试。")
                    }
                    mounted();
                }
            })
        }

//bo操作，默认隐藏
        $scope.fileSelected = function (ele) {
            var file = ele.files[0];
            var reader = new FileReader();

            reader.readAsText(file, 'UTF-8');
            reader.onload = function (e) {
                var urlData = this.result;
                $scope.textValue = urlData;
                $scope.$apply();
            };
        }

        $scope.syscBOTempInfo = function () {
            $scope.control.loading = true;
            $http({
                method: "post",
                url: "initBOAndTemplate",
                params: {
                    type: -1
                }
            }).then(function (result) {
                // showMessage("业务对象与模板映射同步成功！");
                getClassList();
                $scope.control.loading = false;
            }, function (err) {
                $scope.control.loading = false;
                showMessage("业务对象与模板映射同步失败，请检查！");
            });
        };

        function addComplete() {
            bootbox.dialog({
                title: "新建模板<span class='modal-line'></span>",
                message: "新建模板已保存？确认将同步模板信息。",
                buttons: {
                    confirm: {
                        label: '确认',
                        className: 'btn-primary',
                        callback: function () {
                            $scope.syscBOTempInfo();
                        }
                    },
                    cancel: {
                        label: '取消',
                        className: 'btn-cancel'
                    }
                }
            });
        }
        //初始化
        created();

        function setSystem(template) {
            if(template.templatecode.indexOf(template.bo_code)===0){
                template.issystem = true;
            }
        }
    }]);




